<?php
/**
 * Created by PhpStorm.
 * User: yuanjie
 * Date: 2016/10/31
 * Time: 下午3:07
 */

$api_service_path = __DIR__ . "/../../../api/";
ob_start();
require_once($api_service_path . "public/index.php");
ob_end_clean();

//获取所有的 执行状态的pos 退款
$auu=AcountUserUndo::where("status",5)->get();
foreach ($auu as $_auu) {
  DB::transaction(function () use ($_auu){
    $tran_no = date('YmdHis',time()).Common::generateCode(8);
    $aur=AcountUserRecharge::find($_auu->aurr_id);
    if($aur->sources==2){//如果是调用pos 暂时只有调用pos才会有这个逻辑
      // $wr=WposRecord::where("type",2)->where("buss_id",$op->id)->first();
      $wr=WposRecord::where("type",1)->where("buss_id",$aur->id)->first();
      $p_r=Pos::statusOrder($wr->id);
      if($p_r->status==0){
        // OrderPayUndo::where("opr_id",$op_id)->update(array("status"=>0,"tran_no"=>"","implement_time"=>null));
        if($p_r->data->trade_status=="REFUND"&&$p_r->data->refund_amount==$aur->amount){
          AcountUserUndo::where("id",$_auu->id)->update(array("status"=>1,"tran_no"=>$tran_no,"implement_time"=>Common::currentTimeString()));
          $wr->trade_status="REFUND";
          $wr->pay_info=$p_r->data->pay_info;
          $wr->return_amont=$aur->amount;
          $wr->save();
          
          //调整各种账务记录
          $uad=UserAccountDeatails::where('account_no',$aur->account_no)->first();
          Account::record($aur->user_id,$aur->shop_id,$uad->acount_type,$tran_no,2,207,$aur->amount,'充值撤销支出,撤销记录：'.$_auu->id."充值记录：".$aur->id);
          //记录了用户的充值消费记录
          $aurs=new AcountUserRechargeSpend;
          $aurs->aurr_id=$aur->id;
          $aurs->user_id=$aur->user_id;
          $aurs->buss_id=$_auu->id;
          $aurs->type=3;//撤销充值消费
          $aurs->amount=$aur->amount;
          $aurs->status=1;
          $aurs->tran_no=$tran_no;
          $aurs->shop_id=$aur->shop_id;
          $aurs->implement_time=date("Y-m-d H:i:s",time());
          $aurs->save();
          $result = array(
              'code' => 1,
              'type' => 1,            
              'order_id' => $aur->id,
              'buss_id' => $wr->buss_id,
          );
          RedisHelper::push($result);
        }
      }
    }
  });
}



//获取所有的 执行装填的订单退款
$opu=OrderPayUndo::where("status",0)->get();
foreach ($opu as $_opu) {
  DB::transaction(function () use ($_opu){
    $tran_no = date('YmdHis',time()).Common::generateCode(8);
    $op=OrderPay::find($_opu->opr_id);//获取该订单退款的 
    $order=Orders::where("order_id",$op->order_id)->first();
    if($op->sources==2){//如果是调用pos 暂时只有调用pos才会有这个逻辑
      $wr=WposRecord::where("type",2)->where("buss_id",$op->id)->first();
      $p_r=Pos::statusOrder($wr->id);
      if($p_r->status==0){
        // OrderPayUndo::where("opr_id",$op_id)->update(array("status"=>0,"tran_no"=>"","implement_time"=>null));
        if($p_r->data->trade_status=="REFUND"&&$p_r->data->refund_amount==$op->amount){
          OrderPayUndo::where("id",$_opu->id)->update(array("status"=>1,"sources"=>2,"tran_no"=>$tran_no,"implement_time"=>Common::currentTimeString()));
          $wr->trade_status="REFUND";
          $wr->pay_info=$p_r->data->pay_info;
          $wr->return_amont=$op->amount;
          $wr->save();
          Account::record($order->pay_user_id,$order->shop_id,1,$tran_no,1,119,$op->amount,'订单支付撤销收入,订单号:'.$order->order_id);
          //记录用户收入
          Account::record($order->pay_user_id,$order->shop_id,1,$tran_no,2,219,$op->amount,'订单支付撤销支出,订单号:'.$order->order_id);
          //记录公司账户支出
          Account::record_base('1',$tran_no,2,219,$op->amount,'订单支付撤销支出,订单号:'.$order->order_id);
          OrderAccount::insert(array('order_id' => $order->order_id,'tran_no' => $tran_no,));
          $op->status=6;
          $op->save();
          if($order->user_id==$order->pay_user_id){
            $temp_op=OrderPay::where("order_id",$order->order_id)->whereIn("status",array(0,1,5,7))->first();      
            if(is_null($temp_op)){//如果没有有未完成的记录
              $order->pay_user_id=0;//如果客户支付 支付记录都删除或撤销 支付用户重置 
            }
          }
          $order->payable_amount=$order->payable_amount-$op->amount;
          $order->save();
          $result = array(
              'code' => 1,
              'type' => 2,            
                'order_id' => $order->order_id,
                'buss_id' => $wr->buss_id,
          );
          RedisHelper::push($result);
        }
      }
    }
  });
}


//获取所有的 执行装填的套餐卡订单退款
$opu=ServiceCardOrderPayUndoRecord::where("status",0)->get();
foreach ($opu as $_opu) {
  DB::transaction(function () use ($_opu){
    $tran_no = date('YmdHis',time()).Common::generateCode(8);
    $op=ServiceCardOrderPayRecord::find($_opu->opr_id);//获取该订单退款的 
    $order=ServiceCardOrder::where("order_id",$op->order_id)->first();
    if($op->sources==2){//如果是调用pos 暂时只有调用pos才会有这个逻辑
      $wr=WposRecord::where("type",5)->where("buss_id",$op->id)->first();
      $p_r=Pos::statusOrder($wr->id);
      if($p_r->status==0){
        // OrderPayUndo::where("opr_id",$op_id)->update(array("status"=>0,"tran_no"=>"","implement_time"=>null));
        if($p_r->data->trade_status=="REFUND"&&$p_r->data->refund_amount==$op->amount){
          ServiceCardOrderPayUndoRecord::where("id",$_opu->id)->update(array("status"=>1,"sources"=>2,"tran_no"=>$tran_no,"implement_time"=>Common::currentTimeString()));
          $wr->trade_status="REFUND";
          $wr->pay_info=$p_r->data->pay_info;
          $wr->return_amont=$op->amount;
          $wr->save();
          Account::record($order->user_id,$order->shop_id,1,$tran_no,1,124,$op->amount,'套餐卡订单结算撤销收入,订单号:'.$order->order_id);
          //记录用户收入
          Account::record($order->user_id,$order->shop_id,1,$tran_no,2,224,$op->amount,'套餐卡订单结算撤销支出,订单号:'.$order->order_id);
          //记录公司账户支出
          Account::record_base('1',$tran_no,2,224,$op->amount,'套餐卡订单结算撤销支出,订单号:'.$order->order_id);
          ServiceCardOrderAccount::insert(array('order_id' => $order->order_id,'tran_no' => $tran_no,));
          $op->status=6;
          $op->save();         
          $order->pay_amount=$order->pay_amount-$op->amount;
          $order->save();
          $result = array(
              'code' => 1,
              'type' => 5,            
              'order_id' => $order->order_id,
              'buss_id' => $wr->buss_id,
          ); 
          RedisHelper::push($result);
        }
      }
    }
  });
}


//获取所有重置记录是 充值中的记录

//获取所有的 执行状态的pos 
$auu=AcountUserRecharge::where("status",5)->where("sources",2)->get();
foreach ($auu as $_auu) {
  DB::transaction(function () use ($_auu){
    $tran_no = date('YmdHis',time()).Common::generateCode(8);
    $aur=AcountUserRecharge::find($_auu->id);
    if($aur->sources==2){//如果是调用pos 暂时只有调用pos才会有这个逻辑
      $wr=WposRecord::where("type",1)->where("buss_id",$aur->id)->first();
      $p_r=Pos::statusOrder($wr->id);
      if($p_r->status==0){
        if($p_r->data->trade_status=="CLOSED"){//如果交易关闭了
          $wr->cashier_trade_no=$p_r->data->cashier_trade_no;
          $wr->mcode=$p_r->data->mcode;
          $wr->device_en=$p_r->data->device_en;
          $wr->trade_status=$p_r->data->trade_status;
          $wr->pay_info=$p_r->data->pay_info;
          $wr->attach=isset($p_r->data->attach)?$p_r->data->attach:"";
          $wr->buyer=isset($p_r->data->buyer)?$p_r->data->buyer:"";
          $wr->thirdSerialNo=isset($p_r->data->thirdSerialNo)?$p_r->data->thirdSerialNo:"";
          $wr->terminalNo=isset($p_r->data->terminalNo)?$p_r->data->terminalNo:"";
          $wr->vouchNo=isset($p_r->data->vouchNo)?$p_r->data->vouchNo:"";
          $wr->batchNo=isset($p_r->data->batchNo)?$p_r->data->batchNo:"";
          $wr->cardType=isset($p_r->data->cardType)?$p_r->data->cardType:"";
          $wr->save();              
          $_auu->status=2;
          $_auu->save();
        }
      }elseif($p_r->status==1004){ //订单不存在
        //查询消息推送情况
        $p_seq = Pos::statusPush($wr->seq_no);
        if($p_seq->status == 0){ //查询成功
            if($p_seq->data->delivery == 1){ //送达
                //查询订单状态
                sleep(11);
                $p_r=Pos::statusOrder($wr->id);
                if($p_r->status==0){ //订单存在
                    if($p_r->data->trade_status=="CLOSED"){//如果交易关闭了
                      $wr->cashier_trade_no=$p_r->data->cashier_trade_no;
                      $wr->mcode=$p_r->data->mcode;
                      $wr->device_en=$p_r->data->device_en;
                      $wr->trade_status=$p_r->data->trade_status;
                      $wr->pay_info=$p_r->data->pay_info;
                      $wr->attach=isset($p_r->data->attach)?$p_r->data->attach:"";
                      $wr->buyer=isset($p_r->data->buyer)?$p_r->data->buyer:"";
                      $wr->thirdSerialNo=isset($p_r->data->thirdSerialNo)?$p_r->data->thirdSerialNo:"";
                      $wr->terminalNo=isset($p_r->data->terminalNo)?$p_r->data->terminalNo:"";
                      $wr->vouchNo=isset($p_r->data->vouchNo)?$p_r->data->vouchNo:"";
                      $wr->batchNo=isset($p_r->data->batchNo)?$p_r->data->batchNo:"";
                      $wr->cardType=isset($p_r->data->cardType)?$p_r->data->cardType:"";
                      $wr->save();              
                      $_auu->status=2;
                      $_auu->save();
                    }
                }elseif($p_r->status==1004){//订单不存在
                    //关闭订单
                    $_auu->status=4;
                    $_auu->save();
                }
            }elseif($p_seq->data->delivery == 0){ //未送达
                //报警
                $phones = Config::get('config.notify_phone');
                $content = '充值记录['.$_auu->id.']取消失败，pos订单不存在且推送未送达，请及时处理。';
                foreach ($phones as $_phone){
                    Sms::send_message('010',$_phone,$content);
                }
            }else{
                //报警
                $phones = Config::get('config.notify_phone');
                $content = '充值记录['.$_auu->id.']取消失败，pos订单不存在且推送状态未知，请及时处理。';
                foreach ($phones as $_phone){
                    Sms::send_message('010',$_phone,$content);
                }
            }
        }else{ //查询不成功
          //报警
          $phones = Config::get('config.notify_phone');
          $content = '充值记录['.$_auu->id.']取消失败，pos订单不存在且推送状态查询失败，请及时处理。';
          foreach ($phones as $_phone){
              Sms::send_message('010',$_phone,$content);
          }
        }
      }
    }
  });
}



//获取所有的 执行状态的pos支付洗车单
$auu=CarWashOrderPayRecord::where("status",5)->where("sources",2)->get();
foreach ($auu as $_auu) {
  DB::transaction(function () use ($_auu){
    $tran_no = date('YmdHis',time()).Common::generateCode(8);
    $aur=CarWashOrderPayRecord::find($_auu->id);
    if($aur->sources==2){//如果是调用pos 暂时只有调用pos才会有这个逻辑
      $wr=WposRecord::where("type",3)->where("buss_id",$aur->id)->first();
      $p_r=Pos::statusOrder($wr->id);
      if($p_r->status==0){
        if($p_r->data->trade_status=="CLOSED"){//如果交易关闭了
          $wr->cashier_trade_no=$p_r->data->cashier_trade_no;
          $wr->mcode=$p_r->data->mcode;
          $wr->device_en=$p_r->data->device_en;
          $wr->trade_status=$p_r->data->trade_status;
          $wr->pay_info=$p_r->data->pay_info;
          $wr->attach=isset($p_r->data->attach)?$p_r->data->attach:"";
          $wr->buyer=isset($p_r->data->buyer)?$p_r->data->buyer:"";
          $wr->thirdSerialNo=isset($p_r->data->thirdSerialNo)?$p_r->data->thirdSerialNo:"";
          $wr->terminalNo=isset($p_r->data->terminalNo)?$p_r->data->terminalNo:"";
          $wr->vouchNo=isset($p_r->data->vouchNo)?$p_r->data->vouchNo:"";
          $wr->batchNo=isset($p_r->data->batchNo)?$p_r->data->batchNo:"";
          $wr->cardType=isset($p_r->data->cardType)?$p_r->data->cardType:"";
          $wr->save();              
          $_auu->status=2;
          $_auu->save();
        }
      }elseif($p_r->status==1004){ //订单不存在
        //查询消息推送情况
        $p_seq = Pos::statusPush($wr->seq_no);
        if($p_seq->status == 0){ //查询成功
            if($p_seq->data->delivery == 1){ //送达
                //查询订单状态
                sleep(11);
                $p_r=Pos::statusOrder($wr->id);
                if($p_r->status==0){ //订单存在
                    if($p_r->data->trade_status=="CLOSED"){//如果交易关闭了
                      $wr->cashier_trade_no=$p_r->data->cashier_trade_no;
                      $wr->mcode=$p_r->data->mcode;
                      $wr->device_en=$p_r->data->device_en;
                      $wr->trade_status=$p_r->data->trade_status;
                      $wr->pay_info=$p_r->data->pay_info;
                      $wr->attach=isset($p_r->data->attach)?$p_r->data->attach:"";
                      $wr->buyer=isset($p_r->data->buyer)?$p_r->data->buyer:"";
                      $wr->thirdSerialNo=isset($p_r->data->thirdSerialNo)?$p_r->data->thirdSerialNo:"";
                      $wr->terminalNo=isset($p_r->data->terminalNo)?$p_r->data->terminalNo:"";
                      $wr->vouchNo=isset($p_r->data->vouchNo)?$p_r->data->vouchNo:"";
                      $wr->batchNo=isset($p_r->data->batchNo)?$p_r->data->batchNo:"";
                      $wr->cardType=isset($p_r->data->cardType)?$p_r->data->cardType:"";
                      $wr->save();              
                      $_auu->status=2;
                      $_auu->save();
                    }
                }elseif($p_r->status==1004){//订单不存在
                    //关闭订单
                    $_auu->status=4;
                    $_auu->save();
                }
            }elseif($p_seq->data->delivery == 0){ //未送达
                //报警
                $phones = Config::get('config.notify_phone');
                $content = '洗车订单['.$_auu->order_id.']取消失败，pos订单不存在且推送未送达，请及时处理。';
                foreach ($phones as $_phone){
                    Sms::send_message('010',$_phone,$content);
                }
            }else{
                //报警
                $phones = Config::get('config.notify_phone');
                $content = '洗车订单['.$_auu->order_id.']取消失败，pos订单不存在且推送状态未知，请及时处理。';
                foreach ($phones as $_phone){
                    Sms::send_message('010',$_phone,$content);
                }
            }
        }else{ //查询不成功
          //报警
          $phones = Config::get('config.notify_phone');
          $content = '洗车订单['.$_auu->order_id.']取消失败，pos订单不存在且推送状态查询失败，请及时处理。';
          foreach ($phones as $_phone){
              Sms::send_message('010',$_phone,$content);
          }
        }
      }
    }
  });
}


//获取所有的 执行状态的收回但撤销记录
$opu=ReceivablePayUndo::where("status",0)->get();
foreach ($opu as $_opu) {
  DB::transaction(function () use ($_opu){
    $tran_no = date('YmdHis',time()).Common::generateCode(8);
    $op=ReceivablePay::find($_opu->rpr_id);//获取该退款的那的 支付记录 
    $receivable=Receivable::find($op->receivable_id);
    if($op->sources==2){//如果是调用pos 暂时只有调用pos才会有这个逻辑
      $wr=WposRecord::where("type",4)->where("buss_id",$op->id)->first();
      $p_r=Pos::statusOrder($wr->id);
      if($p_r->status==0){
        // OrderPayUndo::where("opr_id",$op_id)->update(array("status"=>0,"tran_no"=>"","implement_time"=>null));
        if($p_r->data->trade_status=="REFUND"&&$p_r->data->refund_amount==$op->amount){
          ReceivablePayUndo::where("id",$_opu->id)->update(array("status"=>1,"sources"=>2,"tran_no"=>$tran_no,"implement_time"=>Common::currentTimeString()));
          $wr->trade_status="REFUND";
          $wr->pay_info=$p_r->data->pay_info;
          $wr->return_amont=$op->amount;
          $wr->save();

          if($receivable->type==2){//如果是起初回收
              $ba=BeginArrear::where("shop_id",$receivable->shop_id)->where("company_id",$receivable->company_id)->lockForUpdate()->first();
              Account::record($receivable->company_id,0,3,$tran_no,2,225,$op->amount,'期初回收撤销支出,收回单号:'.$receivable->receivable_id);
              //记录用户收入
              Account::record_base('1',$tran_no,2,225,$op->amount,'期初回收撤销支出,收回单号:'.$receivable->receivable_id);
              $ba->current_amount=$ba->current_amount+$op->amount;
              $ba->save();
          }else{//如果是订单回收
              //记录用户充值 不记录充值记录  只记录流水
              Account::record($receivable->company_id,0,3,$tran_no,2,226,$op->amount,'订单回收撤销支出,收回单号:'.$receivable->receivable_id);
              //记录用户支出
              Account::record_base('1',$tran_no,2,226,$op->amount,'订单回收撤销支出,收回单号:'.$receivable->receivable_id);
          }
          $op->status=6;
          $op->save();     

          $result = array(
              'code' => 1,
              'type' => 4,            
              'order_id' => $op->receivable_id,
              'buss_id' => $wr->buss_id,
          ); 
          RedisHelper::push($result);
        }
      }
    }
  });
}
// $p_r=Pos::statusOrder(14981238247464);
// var_dump($p_r);